/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.starter.web.framework.flow;

import cn.hallele.ms.starter.web.framework.context.ActionContext;
import cn.hallele.ms.starter.web.framework.node.ServiceFlow;
import cn.hallele.ms.starter.web.framework.service.ActionInitializeService;
import cn.hallele.ms.starter.web.framework.service.ActionService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.flow.LiteflowResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/12/23 23:33
 */
@Slf4j
@LiteflowComponent
public class FinishedFlow extends ServiceFlow {
    @Autowired(required = false)
    private ActionInitializeService actionInitializeService;

    @Override
    public void process() throws Exception {
        ActionContext context = this.getContextBean(ActionContext.class);

        saveOrder(context);
    }

    private void saveOrder(ActionContext context) {
        ActionService actionService = context.getActionService();
        if (!actionService.needCreateOrder()) {
            return;
        }

        LiteflowResponse chainResponse = context.getChainResponse();

        if (chainResponse.isSuccess()) {
            context.setOrder(actionInitializeService.completeActionOrder(context));
            return;
        }

        context.setOrder(actionInitializeService.cancelActionOrder(context));
    }
}
